﻿#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Foundation;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
#else
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
#endif

namespace FreshMeat.Xaml
{
#if !SILVERLIGHT && !NETFX_CORE
   public class HorizontalLine : Shape
   {
      readonly LineGeometry lineGeometry = new LineGeometry();

      protected override Geometry DefiningGeometry
      {
         get { return lineGeometry; }
      }

      static HorizontalLine()
      {
         // ReSharper disable RedundantCast
         StretchProperty.OverrideMetadata(typeof(HorizontalLine), new FrameworkPropertyMetadata((object)Stretch.Fill));
         // ReSharper restore RedundantCast
      }

      protected override Size ArrangeOverride(Size finalSize)
      {
         lineGeometry.EndPoint = new Point(finalSize.Width, 0);

         return base.ArrangeOverride(finalSize);
      }
   }
#else
   public class HorizontalLine : Path
   {
      Size previousSize;

      public HorizontalLine()
      {
         Stretch = Stretch.Fill;
         CreateGeometry(0);
      }

      protected override Size ArrangeOverride(Size finalSize)
      {
         // ReSharper disable CompareOfFloatsByEqualityOperator
         if (previousSize.Width != finalSize.Width || previousSize.Height != finalSize.Height)
            CreateGeometry(finalSize.Width);
         previousSize = finalSize;
         // ReSharper restore CompareOfFloatsByEqualityOperator

         return finalSize;
      }

      void CreateGeometry(double width)
      {
         // Must stay INSIDE the final arrange size, including the stroke thickness.
         // Otherwise, another layout is triggered which results in a layout cycle exception.
         var figure = new PathFigure { StartPoint = new Point(0 + 0.5 * StrokeThickness, 0 + 0.5 * StrokeThickness) };
         var segment = new LineSegment {Point = new Point(width - 0.5 * StrokeThickness, 0 + 0.5 * StrokeThickness)};
         figure.Segments.Add(segment);
         figure.IsClosed = false;

         var geometry = new PathGeometry();
         geometry.Figures.Add(figure);
         
         Data = geometry;
      }
   }
#endif
}
